import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { getRoleList, create, update, del } from "@/api/roleApi";
import {
  getRbacMenuListTreeApi
} from "@/api/menu";
import {
	getRoleShow
} from "@/api/roleApi"
import { type Ref, reactive, ref, onMounted, h, toRaw } from "vue";

export function useRole(treeRef: Ref) {
  const form = reactive({
    page: 1,
    perPage: 10,
    name: "",
    permissionChar: "",
    status: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "rbacRoleId"
    },
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "备注",
      prop: "remarks"
    },
    {
      label: "创建时间",
      prop: "createAt",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];
  function handleDelete(row) {
    del({ rbacRoleId: row.rbacRoleId })
      .then(() => {
        message(`删除成功`, { type: "success" });
        onSearch();
      })
      .catch(error => {
        message(`删除失败:` + error.response.data.msg ?? "", {
          type: "error"
        });
      });
    onSearch();
  }

  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getRoleList(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getRoleList(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getRoleList(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  async function openDialog(title = "新增", row?: FormItemProps) {
    let formInline = {};
	const menu = await getRbacMenuListTreeApi();
    if (`${title}` == "新增") {
      formInline = {
        title: "新增",
		menuIdsOptions: menu.result,
        name: row?.name ?? "",
        sort: row?.sort ?? 1,
        remarks: row?.remarks ?? "",
        menuIds: [1]
      };
    } else {
		const { result } = await getRoleShow({ rbacRoleId: row?.rbacRoleId });
      formInline = {
        title: "修改",
		menuIdsOptions: menu.result,
        rbacRoleId: row?.rbacRoleId ?? "",
        name: result?.name ?? "",
        sort: result?.sort ?? 1,
        remarks: result?.remarks ?? "",
        menuIds: result?.menuIds ?? [1]
      };
    }
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: formInline
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了角色名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              create(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              update(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  onMounted(async () => {
    onSearch();
  });
  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    onQueryChanged,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
